﻿using Caliburn.Micro;
using SD.Infrastructure.DTOBase;
using SD.Infrastructure.WPF.Caliburn.Aspects;
using SD.Infrastructure.WPF.Caliburn.Base;
using SD.Infrastructure.WPF.Models;
using SD.IOC.Core.Mediators;
using SlamDunk.MES.Client.ViewModels.Facility;
using SlamDunk.MES.IAppService.DTOs.Outputs.PlanContext;
using SlamDunk.MES.IAppService.DTOs.Outputs.ResourceContext;
using SlamDunk.MES.IAppService.Interfaces;
using SlamDunk.MES.Presentation.Models.NotifyModels;
using SlamDunk.MES.ReportView.Models;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.ServiceModel.Extensions;
using System.Threading;
using System.Threading.Tasks;

namespace SlamDunk.MES.Client.ViewModels.Report
{
    /// <summary>
    /// 设备台时统计ViewModel
    /// </summary>
    public class WorkOrderActualEquipmentsReportViewModel : ScreenBase
    {
        #region # 字段及构造器
        /// <summary>
        /// 作业管理服务契约接口代理
        /// </summary>
        private readonly ServiceProxy<IExecutionContract> _iExecutionContract;

        /// <summary>
        /// 资源定义服务契约接口代理
        /// </summary>
        private readonly ServiceProxy<IResourceContract> _iResourceContract;

        /// <summary>
        /// 计划管理服务契约接口代理
        /// </summary>
        private readonly ServiceProxy<IPlanContract> _planContract;

        /// <summary>
        /// 报表统计服务契约接口代理
        /// </summary>
        private readonly ServiceProxy<IReportContract> _iReportContract;

        /// <summary>
        /// 窗口管理器
        /// </summary>
        private readonly IWindowManager _windowManager;

        /// <summary>
        /// 依赖注入构造器
        /// </summary>
        public WorkOrderActualEquipmentsReportViewModel(ServiceProxy<IExecutionContract> iExecutionContract, ServiceProxy<IResourceContract> iResourceContract, ServiceProxy<IPlanContract> planContract, ServiceProxy<IReportContract> iReportContract, IWindowManager windowManager)
        {
            this._iExecutionContract = iExecutionContract;
            this._iResourceContract = iResourceContract;
            this._planContract = planContract;
            this._iReportContract = iReportContract;
            this._windowManager = windowManager;
        }
        #endregion

        #region 属性

        #region 开始时间 —— DateTime? StartTime
        /// <summary>
        /// 开始时间
        /// </summary>
        [DependencyProperty]
        public DateTime? StartTime { get; set; }
        #endregion

        #region 结束时间 —— DateTime? EndTime
        /// <summary>
        /// 结束时间
        /// </summary>
        [DependencyProperty]
        public DateTime? EndTime { get; set; }
        #endregion

        #region 设备列表
        /// <summary>
        /// 设备列表
        /// </summary>
        [DependencyProperty]
        public ObservableCollection<EquipmentInfo> Equipments { get; set; }
        #endregion

        #region 已选设备
        /// <summary>
        /// 已选设备
        /// </summary>
        [DependencyProperty]
        public EquipmentInfo SelectedEquipment { get; set; }
        #endregion

        #region 已选工厂模型 —— Node SelectedFacility
        /// <summary>
        /// 已选工厂模型
        /// </summary>
        [DependencyProperty]
        public Node SelectedFacility { get; set; }
        #endregion

        #region 设备统计列表
        /// <summary>
        /// 设备统计列表
        /// </summary>
        [DependencyProperty]
        public ObservableCollection<EquipmentSummaryNm> EquipmentSummaryReports { get; set; }
        #endregion
        #endregion

        #region # 方法

        //Initializations

        #region 初始化 —— override async Task OnInitializeAsync(CancellationToken cancellationToken)
        /// <summary>
        /// 初始化
        /// </summary>
        protected override async Task OnInitializeAsync(CancellationToken cancellationToken)
        {
            IEnumerable<EquipmentInfo> equipments = await Task.Run(() => this._iResourceContract.Channel.GetEquipmentsByPage(null, null, null, 1, int.MaxValue).Datas, cancellationToken);
            this.Equipments = new ObservableCollection<EquipmentInfo>(equipments);

            StartTime = DateTime.Now.AddDays(-30);
            EndTime = DateTime.Now;
            await this.ReloadEquipmentSummaryReports();
        }
        #endregion

        //Actions
        #region 选择工厂模型 —— async void SelectFacility()
        /// <summary>
        /// 选择工厂模型
        /// </summary>
        public async void SelectFacility()
        {
            this.Busy();

            SelectFacilityViewModel viewModel = ResolveMediator.Resolve<SelectFacilityViewModel>();
            bool? result = await this._windowManager.ShowDialogAsync(viewModel);
            if (result == true)
            {
                this.SelectedFacility = viewModel.SelectedFacility;
            }

            this.Idle();
        }
        #endregion

        #region 清空工厂模型 —— async void ClearFacility()
        /// <summary>
        /// 清空工厂模型
        /// </summary>
        public async void ClearFacility()
        {
            this.SelectedFacility = null;
        }
        #endregion

        #region 查看设备台时统计 —— async void LoadEquipmentSummaryReport()
        /// <summary>
        /// 查看设备台时统计
        /// </summary>
        public async void LoadEquipmentSummaryReport()
        {
            await this.ReloadEquipmentSummaryReports();
        }
        #endregion

        #region 查看明细
        /// <summary>
        /// 查看明细
        /// </summary>
        public async void LookEquipmentSummaryReport(EquipmentSummaryNm equipmentSummaryNm)
        {
            this.Busy();
            WorkOrderActualEquipmentsDetailtReportViewModel viewModel = ResolveMediator.Resolve<WorkOrderActualEquipmentsDetailtReportViewModel>();
            viewModel.Load(equipmentSummaryNm);
            bool? result = await this._windowManager.ShowDialogAsync(viewModel);
            this.Idle();
        }
        #endregion 
        //Private

        #region 加载设备台时列表 —— async Task ReloadEquipmentSummaryReports()
        /// <summary>
        /// 加载设备台时列表
        /// </summary>
        private async Task ReloadEquipmentSummaryReports()
        {
            EquipmentSummaryReports = new ObservableCollection<EquipmentSummaryNm>();
            this.Busy();
            DateTime? startTime = this.StartTime;
            DateTime? endTime = this.EndTime;
            Guid? facilityId = this.SelectedFacility?.Id;
            //查询生成计划
            PageModel<ExecutionPlanInfo> pageModel = await Task.Run(() => this._planContract.Channel.GetExecutionPlansByPage(
                null,//关键字
                null, //产品Id
                null, //工艺Id
                null, //物料清单Id
                null,//生产计划Id
                null,//作业计划状态
                null, //审核状态
                true, //是否已生成工单
                null, //是否已质检
                startTime,//开始时间
                endTime, //结束时间
                facilityId,//工厂模型Id
                1, //页码
                int.MaxValue));
            //作业计划集合分组
            var executionPlanGroupList = pageModel.Datas.GroupBy(x => new { x.ProductId, x.ProductInfo, x.Status, x.FacilityId, x.FacilityInfo });
            foreach (var executionPlanInfo in pageModel.Datas)
            {
                //获取作业计划设备使用概要列表
                IEnumerable<EquipmentSummaryInfo> equipmentSummaryList = this._iReportContract.Channel.GetExecutionPlanEquipmentUseSummaries(executionPlanInfo.Id);
                foreach (var equipmentSummaryInfo in equipmentSummaryList)
                {
                    //查询集合中是否存在重复员工
                    EquipmentSummaryNm equipmentSummaryReport = EquipmentSummaryReports.SingleOrDefault(x => x.EquipmentId == equipmentSummaryInfo.EquipmentId && x.EquipmentNo == equipmentSummaryInfo.EquipmentNo && x.EquipmentName == equipmentSummaryInfo.EquipmentName);
                    if (equipmentSummaryReport == null)
                    {
                        EquipmentSummaryNm equipmentSummaryNm = new EquipmentSummaryNm();
                        equipmentSummaryNm.EquipmentId = equipmentSummaryInfo.EquipmentId;
                        equipmentSummaryNm.EquipmentNo = equipmentSummaryInfo.EquipmentNo;
                        equipmentSummaryNm.EquipmentName = equipmentSummaryInfo.EquipmentName;
                        equipmentSummaryNm.FacilityId = executionPlanInfo.FacilityId;
                        equipmentSummaryNm.FacilityName = executionPlanInfo.FacilityInfo?.Name;
                        equipmentSummaryNm.Machinehour = equipmentSummaryInfo.Machinehour;
                        equipmentSummaryNm.PlanStartTime = StartTime;
                        equipmentSummaryNm.PlanEndTime = EndTime;
                        equipmentSummaryNm.ExecutionPlanId = executionPlanInfo.Id;
                        ObservableCollection<EquipmentSummaryDetailNm> equipmentSummaryDetailtReportInfos = new ObservableCollection<EquipmentSummaryDetailNm>();

                        EquipmentSummaryDetailNm equipmentSummaryDetailNm = new EquipmentSummaryDetailNm();
                        equipmentSummaryDetailNm.EquipmentNo = equipmentSummaryInfo.EquipmentNo;
                        equipmentSummaryDetailNm.EquipmentName = equipmentSummaryInfo.EquipmentName;
                        equipmentSummaryDetailNm.Machinehour = equipmentSummaryInfo.Machinehour;
                        equipmentSummaryDetailNm.ExecutionPlanNo = executionPlanInfo.Number;
                        equipmentSummaryDetailNm.ExecutionPlanName = executionPlanInfo.Name;
                        equipmentSummaryDetailNm.ProductionBatchNo = executionPlanInfo.ProductionBatchNo;
                        equipmentSummaryDetailtReportInfos.Add(equipmentSummaryDetailNm);
                        equipmentSummaryNm.EquipmentSummaryDetails = equipmentSummaryDetailtReportInfos;
                        EquipmentSummaryReports.Add(equipmentSummaryNm);
                    }
                    else
                    {
                        int index = EquipmentSummaryReports.IndexOf(equipmentSummaryReport);
                        EquipmentSummaryReports.Remove(equipmentSummaryReport);
                        equipmentSummaryReport.Machinehour += equipmentSummaryReport.Machinehour;
                        EquipmentSummaryDetailNm equipmentSummaryDetailNm = new EquipmentSummaryDetailNm();
                        equipmentSummaryDetailNm.EquipmentNo = equipmentSummaryReport.EquipmentNo;
                        equipmentSummaryDetailNm.EquipmentName = equipmentSummaryReport.EquipmentName;
                        equipmentSummaryDetailNm.Machinehour = equipmentSummaryReport.Machinehour;
                        equipmentSummaryDetailNm.ExecutionPlanNo = executionPlanInfo.Number;
                        equipmentSummaryDetailNm.ExecutionPlanName = executionPlanInfo.Name;
                        equipmentSummaryDetailNm.ProductionBatchNo = executionPlanInfo.ProductionBatchNo;
                        equipmentSummaryReport.EquipmentSummaryDetails.Add(equipmentSummaryDetailNm);
                        this.EquipmentSummaryReports.Insert(index, equipmentSummaryReport);
                    }
                }
            }
            if (SelectedEquipment != null)
            {
                EquipmentSummaryReports = new ObservableCollection<EquipmentSummaryNm>(EquipmentSummaryReports.Where(x => x.EquipmentId == SelectedEquipment.Id));
            }
            this.Idle();
        }
        #endregion
        #endregion

    }
}
